import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.share.bean.Person;
import com.share.poi.excel.ExcelUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * created by caifan 2019/3/13
 */
public class Example_01 {

    @Test
    public void dateTimeTest() {
        DateTime now = DateTime.now();
        System.out.println(now.minusDays(5));
        System.out.println(now.minusDays(5-1));
    }

    @Test
    public void timezoneTest() {
        Date date = new Date();
        DateTimeZone dateTimeZone = DateTimeZone.forID("Asia/Shanghai");
        DateTimeZone dateTimeZone1 = DateTimeZone.forID("Asia/Jakarta");
        DateTime dateTime = new DateTime(date.getTime(), dateTimeZone);
        DateTime dateTime1 = new DateTime(date.getTime(), dateTimeZone1);
        System.out.println(dateTime);
        System.out.println(dateTime1);

        System.out.println(date.getTime());

    }

    @Test
    public void readFileTest() throws Exception {
        String str = IOUtils.toString(new FileInputStream("D:/plan.end"));
        System.out.println(str);
    }

    @Test
    public void dateFormatTest() throws Exception {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        String time = "2019-05-01 12:09:09";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime parse = LocalDateTime.parse(time, formatter);
        System.out.println(parse);
        SimpleDateFormat sdf  = new SimpleDateFormat(pattern);
        Date date = sdf.parse(time);
        System.out.println(date.getTime());
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = parse.atZone(zoneId);
        Date from = Date.from(zonedDateTime.toInstant());
        System.out.println(from.getTime());

        org.joda.time.format.DateTimeFormatter dateTimeFormatter1 = DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss");
//        DateTime dateTime1 = DateTime.parse("20190501 12:32:32", dateTimeFormatter1);
//        System.out.println(dateTime1.toDate());
        LocalDate localDate = LocalDate.parse("20190101", DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalTime localTime = LocalTime.parse("12:32:32");
        LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
        System.out.println(localDateTime);
        System.out.println("=================");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate localDate2 = LocalDate.parse("20191011", formatter2);
        LocalDate localDateAfter = localDate2.minusDays(1);
        System.out.println(localDateAfter.format(formatter2));
    }

    @Test
    public void jsonTest() {
        String jsonStr = "[{\"key\":\"answerUnsolve\",\"text\":\"已接听未解决\"}, {\"key\":\"solve\",\"text\":\"已解决\"}, {\"key\":\"unsolve\",\"text\":\"未解决\"}]";
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            System.out.println(json.getString("key") + ":" + json.getString("text"));
        }
    }

    @Test
    public void formatTest() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String format = LocalDateTime.now().format(formatter);
        System.out.println(format);
    }

    private List<Person> getPersons() {
        List<Person> personList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(2017, 3, 6);
        for (int i=0;i<10;i++) {
            Person person = new Person();
            person.setName("zhangsan" + i);
            person.setEmail("zhangsan" + i + "@163.com");
            person.setAge(22 + i);
            person.setAddress("广州市天河区体育西路" + i + "号");
            person.setSalary(5000.23 * i);
            calendar.add(Calendar.DAY_OF_MONTH, i);
            person.setEntryTime(calendar.getTime());
            personList.add(person);
        }
        return personList;
    }

    private JSONArray getColumns() {
        String columns = "[{\"name_en\":\"name\", \"name_cn\":\"姓名\", \"index\":\"0\"}, {\"name_en\":\"age\", \"name_cn\":\"年龄\", \"index\":\"3\"}," +
                "{\"name_en\":\"salary\", \"name_cn\":\"薪资\", \"index\":\"2\"}, {\"name_en\":\"entryTime\", \"name_cn\":\"入职时间\", \"index\":\"1\"}]";
        return JSONArray.parseArray(columns);
    }

    @Test
    public void export() throws Exception {
        JSONArray columns = getColumns();
        List<Person> persons = getPersons();
        ExcelUtils.createExcel(columns, persons, "D:/test/abcde.xlsx");
    }

    @Test
    public void listTest() {
        List<Person> personList = new ArrayList<>();
        Person person = new Person();
        person.setEntryTime(new Date());
        person.setSalary(10000.00d);
        person.setAddress("shanghai");
        personList.add(person);

        System.out.println(ToStringBuilder.reflectionToString(personList.get(0)));
        for (Person person1 : personList) {
            person1.setSalary(person1.getSalary() * 2);
            person1.setAddress("guangzhou");
        }
        System.out.println(ToStringBuilder.reflectionToString(personList.get(0)));
    }

    @Test
    public void fileTest() {
        System.out.println(System.getProperty("java.io.tmpdir"));
    }

    @Test
    public void compareDateTest() throws Exception {
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person();
        person1.setAddress("shanghai");
        Calendar c1 = Calendar.getInstance();
        c1.set(2019, 0, 2);
        person1.setEntryTime(c1.getTime());
        person1.setAge(22);
        c1.set(2019, 05, 25);
//        person1.setGraduateTime(formatDate(c1.getTime()));
//        personList.add(person1);

        Person person2 = new Person();
        person2.setAddress("wuhan");
        Calendar c2 = Calendar.getInstance();
        c2.set(2017, 6, 14);
        person2.setEntryTime(c2.getTime());
        person2.setAge(22);
        c2.set(2019, 05, 26);
//        person2.setGraduateTime(formatDate(c2.getTime()));
//        personList.add(person2);

        Person person3 = new Person();
        person3.setAddress("guangzhou");
        Calendar c3 = Calendar.getInstance();
        c3.set(2019, 5, 22);
        person3.setEntryTime(c1.getTime());
        person3.setAge(22);
        c3.set(2019, 05, 20);
        person3.setGraduateTime(formatDate(c3.getTime()));
//        personList.add(person3);

        Person person4 = new Person();
        person4.setAddress("beijing");
        Calendar c4 = Calendar.getInstance();
        c4.set(2019, 6, 1);
        person4.setEntryTime(c4.getTime());
        person4.setAge(22);
        c4.set(2019, 6, 12);
//        person4.setGraduateTime(formatDate(c4.getTime()));
        personList.add(person4);

        System.out.println(personList);

        //personList = personList.stream().sorted(Comparator.comparing(Person::getGraduateTime).reversed()).sorted(Comparator.comparing(Person::getEntryTime).reversed()).collect(Collectors.toList());

        Collections.sort(personList, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if (null == o1.getGraduateTime() && null != o2.getGraduateTime()) {
                    return 1;
                } else if (null != o1.getGraduateTime() && null == o2.getGraduateTime()) {
                    return -1;
                } else if (null != o1.getGraduateTime() && null != o2.getGraduateTime()){
                    return o2.getGraduateTime().compareTo(o1.getGraduateTime());
                } else {
                    return 0;
                }
            }
        });

        Collections.sort(personList, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o2.getEntryTime().compareTo(o1.getEntryTime());
            }
        });
        System.out.println("===========");
        System.out.println(personList);
    }

    @Test
    public void dateTime1Test() throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-00 00:00:00");
        Calendar calendar = Calendar.getInstance();
        calendar.set(2018, 05, 22);
        String time1 = format.format(calendar.getTime());
        calendar.set(2018, 05, 20);
        String time2 = format.format(calendar.getTime());
        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);
        System.out.println(date1.compareTo(date2));
    }

    private Date formatDate(Date date) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();
//        calendar.set(2018, 05, 22);
//        String time1 = format.format(calendar.getTime());
        String time1 = format.format(date);
        return format.parse(time1);
    }

    @Test
    public void qianbaoTest() throws Exception {
        String url = "https://ipaytest.fortunebill.com/mas/file/stdata.do";
        String Key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtwz5WQBNA+R/k9ZELlELhle7IAWEATxGkg7As04xdkOgba1nEKYXD7/BrBnjEvITgnAcIT79Xz4vhtHu06FxcnXrEF7wuiUc5fFUwJiGQFlsbxlhue4z3PZ86QfP8f1RhcADMtPwQ3tE6fQNyzgwbkDRmJu/YXI0O62ahTWPOmCz+Vbfp6NzSo1+je3bnLNE8ozZP1GR4BoRwZcOKmTujeIe6d33BYZ9CqwrC4g9NJupl42+f5vR2q0aObsRILFuC+4uXsc4OOrWXxkldFnbyYrPMMm1otQVifg4Ppm/3u0IbdxkIcXqamTAwXJxokxzyenjCxJQHWmu1ApL6SZRlAgMBAAECggEAEOT+1pv8Q0D1nOlTZPDRX+WYBdI8gC8v4/L52iHnb+F678+MNspiux5FHeLPMzGxKbWB6Yj3ba48R4Go1XoSIN8e5Jn6Lfwi9K/mCHxsnvnNefHa/0L7/b38EUoAUvh+V8rwCPc/2tQPO8ST5UGrY7KtpZD7mOnGvUCeBejkX127TTn/mgWqJgAmsOhxGFVV781Z0etODvI1QX1seH30PgONG7xsUSR83804DdJFy9H2Hqj7phxDSyH/lRlwndwQ8+mXyHSzHSm0KJZxZQOElj0LExqIMAIXCms9VwPs8u7VIcb2b8UiNG6OiMiTZhgmXhDNDl0k2G6pUsFLYpGHsQKBgQDfeEikeio/YHBE+/U21JwbZE4j9KBPDQePkTbkV57xc3o/x832YvUApoapOmA03MXfM0w0WJ6rc7ysJvLYRZCV1Mcai3bXbRAtEDmORcvYCoWNrXUHK/wtkhFeGMmyILmbIxTbUC4I8XXffQwZ7NtT7h+noMdp3FX4N9tPGcGA+wKBgQDHDpixkUfZPbfRK6g9JhLJ4yDHLTJ6P8GPUdFDj8RDmZVgkGk+1C/0F6OAv4jwiCxBVF/bYAjARwSry+HmQMXskk0KmPygvUGfGLiF64sot+iqsbf2xJXZFE9y951tDVU3GK5n3/lw9Hoi7TQO1JrXEeMg4AMkeugYy6HLrTsCHwKBgCuyaon29XHlGq7ykbWCB3B3wavYNsyeYJ8bJx+pXoQaL4pvOH/4Q6434dcPeiZ8ERke/8Swm34tKHSFPTE7ERWrQK+ZG8juI56cMJT4Yu7Ax/K3O04GtM34ZPsAX9g7++8xAfAMkqPfC0yDOC2NmimkQ35UuwmhMxJRYcnq4GKnAoGAUPENg/7YYWzoRwTil2LY9wEFfhhR00YDlhyl5DwciYR1Klvuf97WVQIbuSmpLG2i2TnO9Kx7QnxeWOFBzVf/Y3AmJa4J4+6xNVlfBw29e2Q1FtvHO2+6oxfQKqanfAWU5h+CI7j+fEDdPUCJD5LCF7wtSFvuyzGzGQoMk36wZO8CgYEAzgo7x/v534U++u1JdjAJ2ycraPNBo7d01w1q7qpXam7AWdLYaEgIi18T4ZzShSCpWdBupwlS/LCkChNjqJ9asSvRxGDZiASCmA1Uh7+YWTQhyM7jH7Ff6OO8dg/yaMcDIJt8w19tgWGCvOscLIs1x9YlZem3lgG9Dqp+locPvLM=";
        Map<String, String> treeMap = new TreeMap<>();
        treeMap.put("version", "1.0");
        treeMap.put("merchantNo", "666100000000888");
        treeMap.put("orderDate", "20190702");
        treeMap.put("signType", "RSA2");
        treeMap.put("digest", RsaUtils.sign(treeMap, Key, "RSA2"));

        CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(60 * 1000).setConnectionRequestTimeout(60 * 1000)
                .setSocketTimeout(60 * 1000).setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : treeMap.keySet()) {
            String value = treeMap.get(key);
            if(StringUtils.isNotBlank(value)) {
                nvps.add(new BasicNameValuePair(key, value));
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
//            logger.info("httpPost ===**********===>>> " + EntityUtils.toString(httpPost.getEntity()));
            HttpResponse response = httpClient.execute(httpPost);
            String strResult = "";
            if (response.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(response.getEntity());
                System.out.println(strResult);
            } else {
                System.out.println( "Error Response: " + response.getStatusLine().toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println( "post failure :caused by-->" + e.getMessage().toString());
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void distinctTest() {
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person();
        person1.setName("zhangsan");
        person1.setAge(22);
        person1.setAddress("北京");
        Person person2 = new Person();
        person2.setName("zhangsan");
        person2.setAge(32);
        person2.setAddress("北京1");
        Person person3 = new Person();
        person3.setName("lisi");
        person3.setAge(22);
        person3.setAddress("上海");
        Person person4 = new Person();
        person4.setName("wangwu");
        person4.setAge(24);
        person4.setAddress("广州");
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);
        Map<String, String> map = personList.stream().collect(Collectors.toMap(Person::getName, Person::getAddress));
        System.out.println(JSONObject.toJSONString(personList));

        personList = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(person -> {
            return person.getName() + "," + person.getAddress();
        }))), ArrayList::new));
        System.out.println(JSONObject.toJSONString(personList));

    }

    @Test
    public void bigDecimalTest() {
        BigDecimal num1 = BigDecimal.ZERO;
        BigDecimal num2 = BigDecimal.ZERO;
        num1 = num1.add(new BigDecimal(3L));
        num2 = num2.add(new BigDecimal(5.6));
        System.out.println(num1.compareTo(num2));
        System.out.println(num2.setScale(2, RoundingMode.HALF_UP));
    }

    @Test
    public void parseStringTest() {
        String expr = "${abc} > 5";
        Integer abc = 7;
        Map<String, Object> map = new HashMap<>();
        map.put("abc", 7);
        int prefixIndex = expr.indexOf("${");
        int suffixIndex = expr.indexOf("}");
        String exp = expr.substring(prefixIndex, suffixIndex+1);
        String replaceExp = exp.substring(prefixIndex+2, suffixIndex);
        expr = expr.replace(exp, map.get(replaceExp).toString());
        System.out.println(expr);
    }

    @Test
    public void listTest_01() {
        List<Person> persons = getPersons();
        System.out.println(JSONObject.toJSON(persons));
        persons.sort(Comparator.comparing(Person::getEntryTime).reversed());
        System.out.println(JSONObject.toJSON(persons));
    }


    @Test
    public void StringJoinerTest() {
        StringJoiner joiner = new StringJoiner(":", "[", "]");
        joiner.add("beijing").add("shanghai").add("guangzhou");
        System.out.println(joiner.toString());
    }

    @Test
    public void reduceTest() {
        List<Integer> integers = Arrays.asList(1, 3, 4, 6);
        System.out.println(integers.stream().reduce((a, b) -> a + b).get());

        List<BigDecimal> bigDecimals = Arrays.asList(new BigDecimal(23), new BigDecimal(12.13), new BigDecimal(10));
        System.out.println(bigDecimals.stream().reduce((a, b) -> a.add(b)).get().setScale(2, BigDecimal.ROUND_HALF_EVEN));
    }

    @Test
    public void linkTest() throws Exception {
        String link = "https://sycm.taobao.com/flow/gray/excel.do?spm=a21ag.11910098.0.0.36f7410cbu32YW&_path_=v4/excel/shop/source&device=2&dateType=day&dateRange=2021-03-10|2021-03-10&belong=all";
        StringBuffer newLink = new StringBuffer();
        String param = "dateRange=";
        int index = link.indexOf(param);
        String start = link.substring(0, index) + param;
        int lastIndex = link.lastIndexOf("&");
        String update = link.substring(index + param.length(), lastIndex);
        String end = link.substring(lastIndex);
        for (int i=0; i < 40; i++) {
            String date = getDateAdd(i);
            newLink.append(start).append(date).append("|").append(date).append(end).append("\n");
        }
        /*System.out.println(start);
        System.out.println(update);
        System.out.println(end);*/
        PrintWriter pw = new PrintWriter("D:/test/test.txt");
        pw.write(newLink.toString());
        pw.flush();
        pw.close();
    }

    private String getDateAdd(int add) {
        LocalDateTime localDateTime = LocalDateTime.of(2021, 2, 5, 0, 0);
        localDateTime = localDateTime.plusDays(add);
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    @Test
    public void getDate() {
        System.out.println(getDateAdd(2));
    }

    @Test
    public void subTest() {
        String str = "【生意参谋平台】无线店铺流量来源-2021-02-05_2021-02-05.xls";
        System.out.println(str.indexOf("_"));
        System.out.println(str.lastIndexOf("."));
    }

}
